package com.hzw.net.utils.recyclerview

import android.graphics.Rect
import android.view.View
import androidx.annotation.DimenRes
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.hzw.core.resources.appDimen

/**
 * Copyright (c) 2019, 四川绿源集科技有限公司 All rights reserved.
 * author：HuaZhongWei
 * date：2020/05/06
 * description： recyclerView的LinearLayout布局时item间距
 */
class CommonLinearLayoutItemDecoration(
    //顶部
    private val topValue: Float = 0f,
    //底部
    private val bottomValue: Float = 0f,
    //顶部
    private val startValue: Float = 0f,
    //底部
    private val endValue: Float = 0f,
    //垂直间隔
    private val spacingVValue: Float = 0f
) : ItemDecoration() {

    constructor(
        //顶部
        @DimenRes top: Int = 0,
        //底部
        @DimenRes bottom: Int = 0,
        //顶部
        @DimenRes start: Int = 0,
        //底部
        @DimenRes end: Int = 0,

        @DimenRes spacingV: Int = 0
    ) : this(
        topValue = appDimen(top),
        bottomValue = appDimen(bottom),
        startValue = appDimen(start),
        endValue = appDimen(end),
        spacingVValue = appDimen(spacingV)
    )

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {

        //这里是关键，需要根据你有几列来判断
        val position = parent.getChildAdapterPosition(view) // item position

        if ((parent.layoutManager as LinearLayoutManager?)!!.orientation == LinearLayoutManager.VERTICAL) {
            if (position == 0) {
                if (topValue != 0f) {
                    outRect.top = topValue.toInt()
                }
            } else {
                if (spacingVValue != 0f) {
                    outRect.top = spacingVValue.toInt()
                }
            }
            outRect.left = startValue.toInt()
            outRect.right = endValue.toInt()
            if (position == parent.adapter!!.itemCount - 1 && bottomValue != 0f) {
                outRect.bottom = bottomValue.toInt()
            }
        } else {
            if (position == 0) {
                if (startValue != 0f) {
                    outRect.left = startValue.toInt()
                }
            } else {
                if (spacingVValue != 0f) {
                    outRect.left = spacingVValue.toInt()
                }
            }
            outRect.top = topValue.toInt()
            outRect.bottom = bottomValue.toInt()
            if (position == parent.adapter!!.itemCount - 1 && endValue != 0f) {
                outRect.right = endValue.toInt()
            }
        }
    }

}